<?php


namespace app\index\controller;

use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\controller\platform\MpMini;
use app\common\enum\MainEnum;
use app\common\middleware\AuthToken;
use app\common\model\AppTokenModel;
use app\common\model\OrderModel;
use app\common\model\UserCouponModel;
use app\common\model\UserOrderBrokerageModel;
use app\common\model\UserPlatformModel;
use app\common\service\Lang;
use Exception;
use app\common\validate\UsersValidate;
use app\common\exception\ParameterFailedException;
use app\common\model\UserModel;
use app\common\service\Redis;
use think\facade\Db;
use think\Request;
use think\response\Json;
use function Couchbase\basicDecoderV1;

class UserController extends CommonController
{
    protected $middleware = [
        AuthToken::class => ['except' => ['loginMpMini']],
    ];
    /**
     * @return Json
     * @throws Exception
     */
    //    public function register(Request $request): ?\think\response\Json
    //    {
    //        $params = self::getParam(
    //            [
    //                'mobile_number',
    //                'password',
    //            ]
    //        );
    //        (new UsersValidate())->goCheck(__FUNCTION__, $params);
    //
    //        $userModel = UserModel::where('mobile_number', $params['mobile_number'])->field('*')->find();
    //        if ($userModel) {
    //            throw new ParameterFailedException(['msg' => '手机号已存在']);
    //        }
    //        Db::startTrans();
    //        try {
    //            $cryptRes                 = cryptPassword($params['password']);
    //            $userModel                = new UserModel();
    //            $userModel->mobile_number = $params['mobile_number'];
    //            $userModel->password      = $cryptRes['password'];
    //            $userModel->salt          = $cryptRes['salt'];
    //            $userModel->login_ip      = $request->ip();
    //            $userModel->login_time    = NOW_TIME;
    //            $userModel->group_id      = MainEnum::GROUP_USER;
    //            $userModel->save();
    //
    //            $accessToken = RbacService::setToken($userModel->getData('id'));
    //            //            Redis::setAccessToken($accessToken, $userModel->id, 'default');
    //            Db::commit();
    //            return retJson('注册成功', ['access_token' => $accessToken]);
    //        } catch (Exception $e) {
    //            Db::rollback();
    //            throw $e;
    //        }
    //    }

    public function loginMpMini(Request $request)
    {
        Db::startTrans();
        try {
            //            if (!$params['iv'] || !$params['encryptedData'] || !$params['userInfo'] || !$params['rawData']) {
            //                throw new ParameterFailedException(['code' => -3]);
            //            }
            //            if (sha1($params['rawData'] . $wxResult['session_key']) !== $params['signature']) {
            //                throw new ParameterFailedException(['校验数据失败' => -3]);
            //            }
            $params = self::getParam([
                'code',
                'iv',
                'encryptedData',
                'pid',
                'userInfo',
                'rawData',
                'signature',
            ]);
            (new UsersValidate())->goCheck(__FUNCTION__, $params);
            if (!$params['iv'] || !$params['encryptedData']) {
                throw new ParameterFailedException(['code' => -3]);
            }
            $res = MpMini::login($params);
            Db::commit();
            //返回token
            return retJson(Lang::LOGINDone, $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 获取用户列表-分页获取
     * @param string $page
     * @param string $limit
     * @return Json
     * @throws \think\db\exception\DbException
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/7/8
     * @Time: 9:35
     */
    public function getUserList($page = '1', $limit = '10'): Json
    {
        $userListData = (new UserModel())->paginate([
            'page'      => $page,
            'list_rows' => $limit,
        ]);

        return retJson('获取成功', $userListData);
    }

    public function getMyPageInfo(Request $request)
    {
        //积分信息
        //优惠券可使用的数量
        //浏览记录
        Db::startTrans();
        try {

            $models    = (new UserCouponModel())->getUserCouponList($request->userModel->getData('id'));
            $modelsArr = $models->toArray();
            foreach ($modelsArr as $key => $item) {
                if (!UserCouponModel::okUse($item, [], 999999)) {
                    unset($modelsArr[$key]);
                }
            }
            $res = [
                'coupon_count' => count($modelsArr),
                'integral'     => 0,
            ];

            Db::commit();
            return retJson(Lang::GETDone, $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }

    }

    public function getPromoterPageInfo(Request $request)
    {
        /**
         * 今日收益
         *      user_order_brokerage表 当日的总brokerage_price
         * 总收益(可提现+不可提现)
         *      user_order_brokerage表 总brokerage_price
         * 今日订单
         *      user_order_brokerage表 当日的总nb数
         * 累计订单
         *      user_order_brokerage表 总nb数
         * 今日新增用户
         *      所有的用户中的pid是user_id的 当日总量
         * 累计用户
         *      所有的用户中的pid是user_id的 所有总量
         * 可提现金额
         *      总收益 - 已提现金额 - 不可提现金额
         */

        $whereOr            = [
            [
                [
                    'pid',
                    '=',
                    $request->userModel->getData('id'),
                ],
            ],
            [
                [
                    'ppid',
                    '=',
                    $request->userModel->getData('id'),
                ],
            ],
        ];
        $tuiguangUserModels = (new UserPlatformModel())->getUserPlatformList([
            'platform_specific',
            '=',
            $platform_specific = basename(str_replace('\\', '/', get_class(new MpMini()))),
        ], '*', $whereOr);
        /**
         * 今日用户 总用户
         * 今日订单 总订单
         * 今日收益 总收益
         * 可提现收益
         * 本周排名
         */
        // 获取今天00:00
        $todayStart = strtotime(date('Y-m-d' . '00:00:00'));
        // 获取今天24:00
        $todayEnd              = strtotime(date('Y-m-d' . '00:00:00', time() + 3600 * 24));
        $res                   = [];
        $tuiguangUsersToday    = [];
        $tuiguangUsersTodayIds = [];
        $tuiguangUsers         = [];
        $tuiguangUsersIds      = [];
        foreach ($tuiguangUserModels as $tuiguangUserModel) {
            if ($tuiguangUserModel->getData('pid') === $request->userModel->getData('id')) {
                $createTimestamp = strtotime($tuiguangUserModel->getData('bind_pid_time'));
            }
            else {
                $createTimestamp = strtotime($tuiguangUserModel->getData('bind_ppid_time'));
            }
            if ($todayStart < $createTimestamp && $createTimestamp < $todayEnd) {
                #当天的
                $tuiguangUsersToday[]     = $tuiguangUserModel->toArray();
                $tuiguangUsersTodayIds [] = $tuiguangUserModel->getData('user_id');
            }
            # 总的
            $tuiguangUsers[]     = $tuiguangUserModel->toArray();
            $tuiguangUsersIds [] = $tuiguangUserModel->getData('user_id');
        }
        $res['users_today']    = count($tuiguangUsersToday);
        $res['users']          = count($tuiguangUsers);
        $usersTodayOrderModels = (new OrderModel())->getOrderList([
            'user_id',
            'in',
            $tuiguangUsersIds
        ]);



        return retJson(Lang::GETDone, $res);
        //        vd($tuiguangUserModels);
        //--------------------------------
        $orderNbs      = [];
        $orderNbsToday = [];

        $extractedPriceTotal            = $request->userPlatformModel->getData('extracted_brokerage_price_total');
        $canExtractedPriceTotal         = 0;
        $canExtractedPriceTotalToday    = 0;
        $cannotExtractedPriceTotal      = 0;
        $cannotExtractedPriceTotalToday = 0;


        $userOrderBrokerageModels = (new UserOrderBrokerageModel())->getUserOrderBrokerageList($where);
        foreach ($userOrderBrokerageModels as $userOrderBrokerageModel) {
            if (in_array($userOrderBrokerageModel->getData('status'), [
                MainEnum::USER_ORDER_BROKERAGE_STATUS['可提现'],
                MainEnum::USER_ORDER_BROKERAGE_STATUS['订单未完成'],
            ], true)) {
                //全部 = 当天 + 非当天
                $orderNbs[] = $userOrderBrokerageModel->getData('order_nb');

                if ($userOrderBrokerageModel->getData('status') === MainEnum::USER_ORDER_BROKERAGE_STATUS['可提现']) {
                    $canExtractedPriceTotal += $userOrderBrokerageModel->getData('brokerage_price');
                }
                if ($userOrderBrokerageModel->getData('status') === MainEnum::USER_ORDER_BROKERAGE_STATUS['订单未完成']) {
                    $cannotExtractedPriceTotal += $userOrderBrokerageModel->getData('brokerage_price');
                }

                $createTimestamp = strtotime($userOrderBrokerageModel->getData('create_time'));
                if ($todayStart < $createTimestamp && $createTimestamp < $todayEnd) {
                    //当天
                    $orderNbsToday[] = $userOrderBrokerageModel->getData('order_nb');

                    if ($userOrderBrokerageModel->getData('status') === MainEnum::USER_ORDER_BROKERAGE_STATUS['可提现']) {
                        $canExtractedPriceTotalToday += $userOrderBrokerageModel->getData('brokerage_price');
                    }
                    if ($userOrderBrokerageModel->getData('status') === MainEnum::USER_ORDER_BROKERAGE_STATUS['订单未完成']) {
                        $cannotExtractedPriceTotalToday += $userOrderBrokerageModel->getData('brokerage_price');
                    }
                }
            }

        }
        $res['price_total']       = $canExtractedPriceTotal + $cannotExtractedPriceTotal;
        $res['price_total_today'] = $canExtractedPriceTotalToday + $cannotExtractedPriceTotalToday;
        $res['order_total']       = count(array_unique($orderNbs));
        $res['order_total_today'] = count(array_unique($orderNbsToday));
        #可以提取的金额 = 可提取-已提取
        $res['can_extract_price_total'] = $canExtractedPriceTotal - $extractedPriceTotal;
        #不可提取的金额
        $res['cannot_extract_price_total'] = $cannotExtractedPriceTotal;

        $userWhereOr1      = [
            'pid' => $request->userModel->getData('id'),
        ];
        $userWhereOr2      = [
            'ppid' => $request->userModel->getData('id'),
        ];
        $userModels        = (new UserModel())->getUserList([], '*', [
            $userWhereOr1,
            $userWhereOr2,
        ]);
        $newUserTotal      = 0;
        $newUserTotalToday = 0;
        foreach ($userModels as $userModel) {
            $createTimestamp = strtotime($userModel->getData('create_time'));
            #总用户
            $newUserTotal++;
            if ($todayStart < $createTimestamp && $createTimestamp < $todayEnd) {
                #当天注册的用户
                $newUserTotalToday++;
            }
        }

        $res['new_user_total_today'] = $newUserTotalToday;
        $res['new_user_total']       = $newUserTotal;
        return retJson(Lang::GETDone, $res);
    }

    public function getUserInfo(Request $request)
    {
        $res                     = $request->userModel->toArray();
        $res['userPlatformInfo'] = $request->userPlatformModel->toArray();
        return retJson(Lang::GETDone, $res);
    }

    public function putMpMiniPlatformInfo(Request $request)
    {
        Db::startTrans();
        try {
            $params = self::getParam([
                'iv',
                'encryptedData',
                'userInfo',
                'rawData',
                'signature',
            ]);
            MpMini::putMpMiniPlatformInfo($request, $params);
            Db::commit();
            //返回token
            $res                     = $request->userModel->toArray();
            $res['userPlatformInfo'] = $request->userPlatformModel->toArray();
            return retJson(Lang::GETDone, $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}